package com.hefan.api.util;

import javax.servlet.http.HttpServletRequest;

/**
 * HttpServletRequest 工具类
 *
 * @author diguage
 * @since 2016/02/24
 */
public class RequestUtil {
    /**
     * 获取当前页面的URL(带参数)
     *
     * @param req
     * @return
     */
    public static String getCurrentUrl(HttpServletRequest req) {
        String url = getCurrentUrlWithoutParams(req);
        String prmstr = getCurrentUrlParams(req);
        url += "?" + prmstr;
        return url;
    }

    /**
     * 获取当前页面的参数
     *
     * @param request
     * @return
     */
    public static String getCurrentUrlParams(HttpServletRequest request) {
        return request.getQueryString();
    }

    /**
     * 获取当前页面的URL(不带参数)
     *
     * @param request
     * @return
     */
    public static String getCurrentUrlWithoutParams(HttpServletRequest request) {
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
        if (uri == null) {
            return request.getRequestURL().toString();
        }
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String url = scheme + "://" + serverName + ":" + serverPort + uri;
        return url;
    }

    /**
     * 获取当前服务器地址以及端口号
     *
     * @param request
     * @return
     */
    public static String getCurrentServerName(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        return scheme + "://" + serverName + ":" + serverPort;
    }


    /**
     * 获取参数
     *
     * @param request
     * @param name
     * @return
     */
    public static String reqHeader(HttpServletRequest request, String name) {
        String param = request.getHeader(name);
        return param == null ? "" : param;
    }

    public static String getContentFromRequestBody(HttpServletRequest request){
        String result = "";
        java.io.BufferedReader reader = null;
        try {
            reader = request.getReader();// 获得字符流
            StringBuffer content = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line + "\r\n");
            }
            result = content.toString();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                reader = null;
            } catch (Exception e) {

            }
        }
        return result;
    }
}
